<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="引擎名称" prop="engineName">
        <el-input v-model="queryParams.engineName" placeholder="请输入引擎名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="提供商" prop="provider">
        <el-select v-model="queryParams.provider" placeholder="请选择提供商" clearable>
          <el-option v-for="dict in dict.type.tzai_tts_provider" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['tzai:tts:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['tzai:tts:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['tzai:tts:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="engineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="引擎ID" align="center" prop="engineId" width="80" />
      <el-table-column label="引擎代码" align="center" prop="engineCode" width="120" />
      <el-table-column label="引擎名称" align="center" prop="engineName" :show-overflow-tooltip="true" />
      <el-table-column label="提供商" align="center" prop="provider" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tzai_tts_provider" :value="scope.row.provider"/>
        </template>
      </el-table-column>
      <el-table-column label="支持时间戳" align="center" prop="supportTimestamp" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.supportTimestamp === 1" type="success" size="small">支持</el-tag>
          <el-tag v-else type="info" size="small">不支持</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="时间戳级别" align="center" prop="timestampLevel" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.timestampLevel === 'word'" type="success" size="small">词级</el-tag>
          <el-tag v-else-if="scope.row.timestampLevel === 'sentence'" type="warning" size="small">句级</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="调用次数" align="center" prop="callCount" width="100" />
      <el-table-column label="成功率" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.callCount > 0">{{ ((scope.row.successCount / scope.row.callCount) * 100).toFixed(1) }}%</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="默认" align="center" prop="isDefault" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isDefault === 1" type="success" size="small">是</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)" v-hasPermi="['tzai:tts:edit']"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-key" @click="handleManageKeys(scope.row)" v-hasPermi="['tzai:apikey:list']">API Key</el-button>
          <el-button size="mini" type="text" icon="el-icon-video-play" @click="handleTest(scope.row)" v-hasPermi="['tzai:tts:test']">测试</el-button>
          <el-button size="mini" type="text" icon="el-icon-star-on" @click="handleSetDefault(scope.row)" v-hasPermi="['tzai:tts:edit']" v-if="scope.row.isDefault === 0">设为默认</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['tzai:tts:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['tzai:tts:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- API Key管理弹窗 -->
    <api-key-manager
      :show.sync="apiKeyDialogVisible"
      :resource-type="'tts_engine'"
      :resource-id="currentResourceId"
      :resource-name="currentResourceName"
    />

    <!-- 添加或修改TTS引擎对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="引擎代码" prop="engineCode">
              <el-input v-model="form.engineCode" placeholder="请输入引擎代码" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="引擎名称" prop="engineName">
              <el-input v-model="form.engineName" placeholder="请输入引擎名称" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提供商" prop="provider">
              <el-select v-model="form.provider" placeholder="请选择提供商" style="width: 100%">
                <el-option v-for="dict in dict.type.tzai_tts_provider" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="停用"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="API端点" prop="apiEndpoint">
              <el-input v-model="form.apiEndpoint" placeholder="请输入API端点" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-alert
              title="API Key 管理"
              type="info"
              :closable="false"
              show-icon>
              <template slot="default">
                API Key 现已统一在 <el-link type="primary" :underline="false" @click="$router.push('/tzai/api/keypool')">API Key池</el-link> 中管理，请前往配置
              </template>
            </el-alert>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域" prop="region">
              <el-input v-model="form.region" placeholder="如: westus" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支持语言" prop="supportLanguages">
              <el-input v-model="form.supportLanguages" placeholder="如: zh,en" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支持时间戳" prop="supportTimestamp">
              <el-radio-group v-model="form.supportTimestamp">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间戳级别" prop="timestampLevel">
              <el-select v-model="form.timestampLevel" placeholder="请选择时间戳级别" style="width: 100%">
                <el-option label="词级" value="word" />
                <el-option label="句级" value="sentence" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="音色配置" prop="voiceConfig">
              <el-input v-model="form.voiceConfig" type="textarea" placeholder="JSON格式，如：{&quot;zh&quot;:&quot;zh-CN-XiaoxiaoNeural&quot;,&quot;en&quot;:&quot;en-US-JennyNeural&quot;}" :rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="音频参数" prop="audioParams">
              <el-input v-model="form.audioParams" type="textarea" placeholder="JSON格式，如：{&quot;format&quot;:&quot;mp3&quot;,&quot;sampleRate&quot;:16000}" :rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTTSEngine, getTTSEngine, delTTSEngine, addTTSEngine, updateTTSEngine, setDefaultEngine, testConnection, clearCache } from "@/api/tzai/ttsEngine";
import ApiKeyManager from "@/components/ApiKeyManager";

export default {
  name: "TTSEngine",
  dicts: ['tzai_tts_provider'],
  components: {
    ApiKeyManager
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      engineList: [],
      title: "",
      open: false,
      // API Key管理弹窗相关
      apiKeyDialogVisible: false,
      currentResourceId: 0,
      currentResourceName: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        engineName: null,
        provider: null,
        status: null
      },
      form: {},
      rules: {
        engineCode: [
          { required: true, message: "引擎代码不能为空", trigger: "blur" }
        ],
        engineName: [
          { required: true, message: "引擎名称不能为空", trigger: "blur" }
        ],
        provider: [
          { required: true, message: "提供商不能为空", trigger: "change" }
        ],
        apiEndpoint: [
          { required: true, message: "API端点不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listTTSEngine(this.queryParams).then(response => {
        // 确保status、isDefault、supportTimestamp是数字类型
        this.engineList = response.rows.map(item => ({
          ...item,
          status: parseInt(item.status),
          isDefault: parseInt(item.isDefault),
          supportTimestamp: parseInt(item.supportTimestamp)
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        engineId: null,
        engineCode: null,
        engineName: null,
        provider: null,
        apiEndpoint: null,
        region: null,
        supportLanguages: 'zh,en',
        supportTimestamp: 1,
        timestampLevel: 'word',
        voiceConfig: null,
        audioParams: null,
        status: 1,
        remark: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.engineId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加TTS引擎";
    },
    handleUpdate(row) {
      this.reset();
      const engineId = row.engineId || this.ids
      getTTSEngine(engineId).then(response => {
        this.form = {
          ...response.data,
          status: parseInt(response.data.status),
          isDefault: parseInt(response.data.isDefault),
          supportTimestamp: parseInt(response.data.supportTimestamp)
        };
        this.open = true;
        this.title = "修改TTS引擎";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.engineId != null) {
            updateTTSEngine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTTSEngine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const engineIds = row.engineId || this.ids;
      this.$modal.confirm('是否确认删除TTS引擎编号为"' + engineIds + '"的数据项？').then(function() {
        return delTTSEngine(engineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 测试连接 */
    handleTest(row) {
      this.$modal.loading("正在测试连接...");
      testConnection(row.engineId).then(response => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess("连接测试成功");
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },
    /** 设为默认 */
    handleSetDefault(row) {
      this.$modal.confirm('是否将"' + row.engineName + '"设为默认TTS引擎？').then(function() {
        return setDefaultEngine(row.engineId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("设置成功");
      }).catch(() => {});
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.engineName + '"引擎吗？').then(() => {
        return updateTTSEngine(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    /** 管理API Key */
    handleManageKeys(row) {
      this.currentResourceId = row.engineId;
      this.currentResourceName = row.engineName;
      this.apiKeyDialogVisible = true;
    }
  }
};
</script>

